package com.itboye.hutouben.fragment;

import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.itboye.hutouben.R;
import com.itboye.hutouben.activity.store.GoodDetailActivity;
import com.itboye.hutouben.activity.store.GoodsListActivity;
import com.itboye.hutouben.adapter.GoodsListAdapter;
import com.itboye.hutouben.adapter.SouSuoListAdapter;
import com.itboye.hutouben.adapter.SouSuoMall;
import com.itboye.hutouben.adapter.StoreAdapter;
import com.itboye.hutouben.base.BaseFragment;
import com.itboye.hutouben.base.ptr.BasePtr;
import com.itboye.hutouben.bean.GoodsModel;
import com.itboye.hutouben.bean.ZiLeiMuBean;
import com.itboye.hutouben.presenter.ShopMallSearchPresenter;
import com.itboye.hutouben.util.ByAlert;
import com.itboye.hutouben.util.IsUtilUid;
import com.itboye.hutouben.widget.SpringBackListView;
import com.itboye.hutouben.volley.ResultEntity;

import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

import in.srain.cube.views.ptr.PtrDefaultHandler2;
import in.srain.cube.views.ptr.PtrFrameLayout;

/**
 * 商城
 */
public class StoreFragment extends BaseFragment implements Observer{
    PtrFrameLayout commend_anchor_ptr;
    EditText editText;
    TextView tx_search;
    LinearLayout layout;
    PopupWindow mPopWin;
    GridView goods_gridView;
    SpringBackListView goods_listview;

    ShopMallSearchPresenter shopMallSearchPresenter;
    ShopMallSearchPresenter persenter;
    List<ZiLeiMuBean> list;
    StoreAdapter storeAdapter;//类目列表
    private List<SouSuoMall> listBean;

    SouSuoListAdapter adapter;//搜索
    TextView store_line;

    private int selectIndex = 0;//代表选择的那个类目

    private List<GoodsModel.GoodsList> goodsList = new ArrayList<>();
    GoodsListAdapter goodsListAdapter;//商品列表
    int pageIndex = 1;//页码
    int size = 10;//每页的条数
    GoodsModel shopMallSearchBean = new GoodsModel();

    @Override
    public int initView() {
        return R.layout.fragment_store;
    }

    @Override
    public void onMyActivityCreated() {


        BasePtr.setPagedPtrStyle(commend_anchor_ptr);//设置上拉下拉刷新
        persenter = new ShopMallSearchPresenter(this);
        shopMallSearchPresenter = new ShopMallSearchPresenter(this);
        showProgressDialog("加载中,请稍后", true);
        shopMallSearchPresenter.LeiMuQuery("1");
        onListener();
        goodsList = new ArrayList<GoodsModel.GoodsList>();

        commend_anchor_ptr.setPtrHandler(new PtrDefaultHandler2() {
            @Override
            public void onLoadMoreBegin(PtrFrameLayout frame) {
                pageIndex++;
                persenter.shangPinList(pageIndex + "", size + "", list.get(selectIndex).getId(), "", "", "", "", "");
            }

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                persenter.shangPinList(pageIndex + "", size + "", list.get(selectIndex).getId(), "", "", "", "", "");
            }
        });
    }

    /**
     * 操作输入框和List点击事件
     */
    private void onListener() {
        editText.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
        editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {

                if ((event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER) && (event.getAction() == KeyEvent.ACTION_DOWN)) {
                    String searchText = editText.getText().toString();
                    if (searchText.equals("")) {
                        ByAlert.alert(getString(R.string.is_emptyofsearchtext));
                        return false;

                    }
//                    gotoGoodsList(searchText);
                    ByAlert.alert("搜索中");
                    persenter.getMallSouSuo(searchText);
                    return true;
                }
                return false;
            }
        });
        tx_search.setTextSize(15);

        goods_listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //把下标传过去，然后刷新adapter
                selectIndex = position;
                storeAdapter.setIndex(selectIndex);
                storeAdapter.notifyDataSetChanged();
                pageIndex=1;

//                goodsListAdapter = new GoodsListAdapter(goodsList, getActivity());
//                goods_gridView.setAdapter(goodsListAdapter);
                persenter.shangPinList(pageIndex + "", size + "", list.get(selectIndex).getId(), "", "", "", "", "");
                goodsListAdapter.notifyDataSetChanged();
            }
        });

        goods_gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(getActivity(), GoodDetailActivity.class);
                intent.putExtra("goodsId", goodsList.get(position).getId());
                intent.putExtra("goodsName", goodsList.get(position).getName());
                if (goodsList.get(position).getPrice().equals("")) {
                    intent.putExtra("money", "");
                } else {
                    intent.putExtra("money", Double.parseDouble(goodsList.get(position).getPrice()) / 100 + "");
                }
                if (goodsList.get(position).get_group() != null) {
                    if (goodsList.get(position).get_group().size() > 0) {
                        for (int i = 0; i < goodsList.get(position).get_group().size(); i++) {
                            if (goodsList.get(position).get_group().get(i).getG_id().equals("6204")) {
                                intent.putExtra("tehui", "1");
                            }
                        }
                    } else {
                        intent.putExtra("tehui", "2");
                    }
                }else{
                    intent.putExtra("tehui", "2");
                }
                startActivity(intent);
            }
        });
    }

    /**
     * 搜索出的内容
     */
    private void gouwuchePop() {
        layout = (LinearLayout) LayoutInflater.from(getActivity()).inflate(
                R.layout.item_sousuo, null);
        ListView sousuo_listview = (ListView) layout.findViewById(R.id.sousuo_listview);
        LinearLayout kong_layoout = (LinearLayout) layout.findViewById(R.id.kong_layoout);
        TextView kong_text = (TextView) layout.findViewById(R.id.kong_text);
        if (listBean != null) {
            if (listBean.size() > 0) {
                adapter = new SouSuoListAdapter(getActivity(), listBean);
                sousuo_listview.setAdapter(adapter);
                //搜索出的商品列表点击
                sousuo_listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        Intent intent = new Intent(getActivity(), GoodDetailActivity.class);
                        intent.putExtra("goodsId", listBean.get(position).getId() + "");
                        intent.putExtra("goodsName", listBean.get(position).getName());
                        startActivity(intent);
                    }
                });

            } else {
                kong_layoout.setVisibility(View.VISIBLE);
                sousuo_listview.setVisibility(View.GONE);
                kong_text.setText("搜索内容为空");
                return;
            }
        }

        mPopWin = new PopupWindow(layout,
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT, true);
        mPopWin.setBackgroundDrawable(new BitmapDrawable());
        if (!mPopWin.isShowing()) {
            mPopWin.showAsDropDown(store_line, 5, 1);
        }
    }

    void gotoGoodsList(String searchText) {
        Intent intent = new Intent(getActivity(), GoodsListActivity.class);
        intent.putExtra("searchText", searchText);
        startActivity(intent);
    }

    @Override
    public void onClick(View v) {
        String searchText = "";
        switch (v.getId()) {
            case R.id.tx_search:
                searchText = editText.getText().toString();
                if (searchText.equals("")) {
                    ByAlert.alert(getString(R.string.is_emptyofsearchtext));
                    return;
                }
                ByAlert.alert("搜索中");
                persenter.getMallSouSuo(editText.getText().toString());
                break;
        }
    }

    @Override
    public void update(Observable observable, Object data) {
        ResultEntity entity = handlerError(data);
        if (entity != null) {
            IsUtilUid.tianjia(entity);
            //类目列表
            if (entity.getEventType() == ShopMallSearchPresenter.leimu_success) {
                list = (List<ZiLeiMuBean>) entity.getData();
                if (list.size() > 0) {
                    storeAdapter = new StoreAdapter(list, getActivity(), selectIndex);
                    goods_listview.setAdapter(storeAdapter);

                    goodsListAdapter = new GoodsListAdapter(goodsList, getActivity());
                    goods_gridView.setAdapter(goodsListAdapter);
                    persenter.shangPinList(pageIndex + "", size + "", list.get(selectIndex).getId(), "", "", "", "", "");
                }

            } else if (entity.getEventType() == ShopMallSearchPresenter.leimu_fail) {
                ByAlert.alert(entity.getData());
            } else
                //搜索商品
            if (entity.getEventType() == ShopMallSearchPresenter.mall_sousuo_success) {
                listBean = (List<SouSuoMall>) entity.getData();
                if (listBean == null) {
                    ByAlert.alert("暂时没有搜索到相关商品");
                } else if (listBean.size() <= 0) {
                    ByAlert.alert("暂时没有搜索到相关商品");
                } else {
                    gouwuchePop();
                }
            } else if (entity.getEventType() == ShopMallSearchPresenter.mall_sousuo_fail) {
                ByAlert.alert(entity.getData());
            }else
            //商品
            if (entity.getEventType() == ShopMallSearchPresenter.Serach_success) {
                shopMallSearchBean = (GoodsModel) entity.getData();
                if (pageIndex == 1) {
                    goodsList.clear();
                }
                commend_anchor_ptr.refreshComplete();//设置刷新完成

                goodsList.addAll(shopMallSearchBean.getList());
                if (goodsList.size() > 0) {
                    goodsListAdapter.notifyDataSetChanged();
                }
            } else if (entity.getEventType() == ShopMallSearchPresenter.Serach_fail) {
                ByAlert.alert(entity.getData() + " ");
            }
        }
        try {
            closeProgressDialog();
        } catch (Exception e) {
        }
    }

}
